package com.alibaba.algo.utils;

import com.alibaba.algo.constants.OrgConstants;
import com.alibaba.algo.dtos.user.SysOrgTreeNodeDTO;
import org.springframework.util.ObjectUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 树结构工具类
 */
public class TreeUtil {

    /**
     * 根据树节点集合构造组织树型结构
     * @param nodes
     * @return
     */
    public static Set<SysOrgTreeNodeDTO> buildTree(Set<SysOrgTreeNodeDTO> nodes) {
        Map<Long, List<SysOrgTreeNodeDTO>> sub = nodes.stream().filter(node -> !OrgConstants.ROOT_ORG_ID.equals(node.getParentId())).collect(Collectors.groupingBy(SysOrgTreeNodeDTO::getParentId));
        if(!ObjectUtils.isEmpty(nodes)){
            nodes.forEach(node -> node.setChildren(ObjectUtils.isEmpty(sub.get(node.getId())) ? new HashSet<>() : new HashSet<>(sub.get(node.getId()))));
            return nodes.stream().filter(node -> OrgConstants.ROOT_ORG_ID.equals(node.getParentId())).collect(Collectors.toSet());
        }else{
            return new HashSet<>();
        }
    }
}